package priv.wangy.micro.common.utils.secret;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Objects;

/**
 * AES加解密算法
 *
 * @author zhangjq
 * @since 2024-09-10
 */
@Slf4j
public class AesUtil {

    private static final String ALGORITHM = "AES";

    private static final String TRANSFORMATION = "AES/GCM/NoPadding";

    private static final int KEY_SIZE = 256;

    private static final int T_LEN = 128;

    private static final int BLOCK_SIZE = 8192;

    private static final String KEY = "Cte7Uuw0AEnz3QFdt8KlxUwFxLQ/nSGna90UvdMVMsc=";

    private static final String IV = "TyxeCntxRmLdJeFB";

    private static SecretKey generateKey() throws NoSuchAlgorithmException {
        KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
        generator.init(KEY_SIZE, new SecureRandom());
        return generator.generateKey();
    }

    private static GCMParameterSpec generateGcmSpec() {
        byte[] iv = new byte[12];
        SecureRandom random = new SecureRandom();
        random.nextBytes(iv);
        System.out.println(Base64.getEncoder().encodeToString(iv));
        return new GCMParameterSpec(T_LEN, iv);
    }

    public static byte[] encrypt(byte[] data, byte[] key, byte[] iv) throws Exception {
        SecretKeySpec spec = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        GCMParameterSpec gcmSpec = new GCMParameterSpec(T_LEN, iv);
        cipher.init(Cipher.ENCRYPT_MODE, spec, gcmSpec);
        return cipher.doFinal(data);
    }

    public static String encrypt(String data, String key, String iv) {
        try {
            return Base64.getEncoder().encodeToString(encrypt(data.getBytes(StandardCharsets.UTF_8), Base64.getDecoder().decode(key), Base64.getDecoder().decode(iv)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public static String encrypt(String data) {
        return encrypt(data, KEY, IV);
    }

    public static void encryptFile(InputStream fis, OutputStream fos, byte[] key, byte[] iv) throws Exception {
        SecretKeySpec spec = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        GCMParameterSpec gcmSpec = new GCMParameterSpec(T_LEN, iv);
        cipher.init(Cipher.ENCRYPT_MODE, spec, gcmSpec);
        byte[] input = new byte[BLOCK_SIZE];
        int read;
        while ((read = fis.read(input)) != -1) {
            byte[] output = cipher.update(input, 0, read);
            if (output != null) {
                fos.write(output);
            }
        }
        byte[] output = cipher.doFinal();
        if (output != null) {
            fos.write(output);
        }
    }

    public static boolean encryptFile(InputStream fis, OutputStream fos) {
        try {
            encryptFile(fis, fos, Base64.getDecoder().decode(KEY), Base64.getDecoder().decode(IV));
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public static byte[] decrypt(byte[] data, byte[] key, byte[] iv) throws Exception {
        SecretKeySpec spec = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        GCMParameterSpec gcmSpec = new GCMParameterSpec(T_LEN, iv);
        cipher.init(Cipher.DECRYPT_MODE, spec, gcmSpec);
        return cipher.doFinal(data);

    }

    public static String decrypt(String data, String key, String iv) {
        try {
            return new String(decrypt(Base64.getDecoder().decode(data), Base64.getDecoder().decode(key), Base64.getDecoder().decode(iv)), StandardCharsets.UTF_8);
        } catch (Exception e) {
            return null;
        }
    }

    public static String decrypt(String data) {
        return decrypt(data, KEY, IV);
    }

    public static void decryptFile(InputStream fis, OutputStream fos, byte[] key, byte[] iv) throws Exception {
        SecretKeySpec spec = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        GCMParameterSpec gcmSpec = new GCMParameterSpec(T_LEN, iv);
        cipher.init(Cipher.DECRYPT_MODE, spec, gcmSpec);
        byte[] input = new byte[BLOCK_SIZE];
        int read;
        while ((read = fis.read(input)) != -1) {
            byte[] output = cipher.update(input, 0, read);
            if (output != null) {
                fos.write(output);
            }
        }
        byte[] output = cipher.doFinal();
        if (output != null) {
            fos.write(output);
        }
    }

    public static boolean decryptFile(InputStream fis, OutputStream fos) {
        try {
            decryptFile(fis, fos, Base64.getDecoder().decode(KEY), Base64.getDecoder().decode(IV));
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public static void main(String[] args) {
        String encryptStr = encrypt("00");
        System.out.println(encryptStr);
            String realValue = "13339730195";
            String deStr = decrypt(realValue);
            if (Objects.nonNull(deStr)) {

                System.out.println(deStr);
            } else {
                System.out.println(realValue);
            }
    }
}
